//
//  DLAddPswVC.m
//  DontRem
//
//  Created by apple on 2021/1/15.
//

#import "DLAddPswVC.h"
#import "DLChosePswTypeView.h"
#import <PGDatePicker/PGDatePickManager.h>
#import "ImageFactory.h"
#import "DLIconChoseVC.h"
#define M_FontSize floor(AUTO(15))
#define M_Font UIFontMake(M_FontSize)
@interface DLAddPswVC ()<PGDatePickerDelegate>
@property(nonatomic,retain)UIScrollView * bgScro;
@property(nonatomic,retain)UITextField * titleTF, * nameTF, * pswTF, * rePswTF, * urlTF;
@property(nonatomic,retain)QMUITextView * remarkTV;
@property(nonatomic,retain)QMUIButton * choseGroupBtn;
@property(nonatomic,retain)UILabel * dateLab;
@property(nonatomic,retain)NSDate * expirationDate;
@property(nonatomic,assign)NSInteger iconIdx;
@property(nonatomic,retain)UIButton * iconBtn;
@end

@implementation DLAddPswVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor normalColor:UnderLineColor darkColor:UIColorBlack];
    self.myTitle = self.entry?NSLocalizedString(@"Editing", nil):NSLocalizedString(@"Add Record", nil);
    
    [self createUI];
    if (self.entry) {
        [self configEntry];
    }else{
        self.iconIdx = 0;
    }
}
-(void)configEntry{
    self.titleTF.text = self.entry.title;
    self.nameTF.text = self.entry.username;
    self.pswTF.text = self.entry.password;
    self.rePswTF.text = self.entry.password;
    if (self.entry.url.length > 0) {
        self.urlTF.text = self.entry.url;
    }
    if (self.entry.notes.length > 0) {
        self.remarkTV.text = self.entry.notes;
    }
    UIImage *image = [[ImageFactory sharedInstance] imageForIndex:self.entry.image];
    [self.iconBtn setImage:image forState:UIControlStateNormal];
    NSString * datestr = [Mytools dateToDateStr:self.entry.expiryTime];
    if (datestr.length > 10) {
        datestr = [datestr substringToIndex:10];
        self.dateLab.text = datestr;
    }
}
-(void)choseIconClick{
    DLIconChoseVC * vc = [DLIconChoseVC new];
    vc.choseIconIdxBlock = ^(NSInteger idx) {
        UIImage *image = [[ImageFactory sharedInstance] imageForIndex:idx];
        [self.iconBtn setImage:image forState:UIControlStateNormal];
        self.iconIdx = idx;
    };
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)delBtnClick{
    [self.group removeEntry:self.entry];
    if (self.reloadBlock) {
        self.reloadBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)configBtnClick:(UIButton*)sender{
    DLChosePswTypeView * v = [[DLChosePswTypeView alloc]initWithFrame:self.view.bounds point:CGPointMake(sender.center.x, sender.center.y - sender.height/2.0)];
    __block __weak typeof(v)weakV = v;
    v.dismissBlock = ^{
        [weakV removeFromSuperview];
        weakV = nil;
    };
    [self.view addSubview:v];
}
-(void)generatePswClick:(UIButton*)sender{
    int pswCount = [DLUserDefault userDefaultsModel].pswCount;
    NSString * psw = [self generateRandomPswByNum:pswCount];
    XHQHUDSuccessText(NSLocalizedString(@"Generate Password Succeed", nil));
    self.pswTF.text = psw;
    self.rePswTF.text = psw;
}
-(void)choseDate{
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.datePickerMode = PGDatePickerModeDate;
    [self presentViewController:datePickManager animated:false completion:nil];
    datePicker.minimumDate = [NSDate date];
    datePickManager.titleLabel.text = NSLocalizedString(@"Expiration Date", nil) ;
    //设置半透明的背景颜色
    datePickManager.isShadeBackground = true;
    //设置线条的颜色
    datePicker.lineBackgroundColor = UnderLineColor;
    //设置选中行的字体颜色
    datePicker.textColorOfSelectedRow = [UIColor darkGrayColor];
    //设置未选中行的字体颜色
    datePicker.textColorOfOtherRow = UIColorGray;
    //设置取消按钮的字
    datePickManager.cancelButtonText = NSLocalizedString(@"cancel", nil);
    //设置取消按钮的字体大小
    datePickManager.cancelButtonFont = [UIFont boldSystemFontOfSize:17];
    //设置确定按钮的字
    datePickManager.confirmButtonText = NSLocalizedString(@"Sure", nil);
    //设置确定按钮的字体大小
    datePickManager.confirmButtonFont = [UIFont boldSystemFontOfSize:17];
}
#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    self.expirationDate = [gregorian dateFromComponents:dateComponents];
    self.dateLab.text = [NSString stringWithFormat:@"%ld-%02ld-%02ld",dateComponents.year,dateComponents.month,dateComponents.day];
}
-(void)saveBtnClick{
    if (self.titleTF.text.length == 0) {
        XHQHUDErrorText(NSLocalizedString(@"Title should not be empty", nil));
        return;
    }
    if (self.nameTF.text.length == 0) {
        XHQHUDErrorText(NSLocalizedString(@"Account should not be empty", nil));
        return;
    }
    if (self.pswTF.text.length == 0) {
        XHQHUDErrorText(NSLocalizedString(@"Password should not be empty", nil));
        return;
    }
    if(![self.pswTF.text isEqualToString:self.rePswTF.text]){
        XHQHUDErrorText(NSLocalizedString(@"The repeat password is incorrect", nil));
        return;
    }
    VicSingleObject * single = [VicSingleObject getInstance];
    KdbEntry *e = nil;
    if (self.entry) {
        e = self.entry;
        e.image = self.iconIdx;
    }else{
        e = [single.db.kdbTree createEntry:self.group];
        e.image = single.db.kdbTree.root.image;
    }
    e.title = self.titleTF.text;
    e.username = self.nameTF.text;
    e.password = self.pswTF.text;
    if (self.urlTF.text.length) {
        e.url = self.urlTF.text;
    }
    if (self.remarkTV.text.length) {
        e.notes = self.remarkTV.text;
    }
    if (self.expirationDate) {
        e.expiryTime = self.expirationDate;
    }
    
    if(!self.entry){
        [self.group addEntry:e];
    }
    [single.db save];
    if (self.reloadBlock) {
        self.reloadBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)eyeBtnClick:(UIButton*)sender{
    sender.selected = !sender.selected;
    if (sender.isSelected) {
        self.pswTF.secureTextEntry = self.rePswTF.secureTextEntry = NO;
    }else{
        self.pswTF.secureTextEntry = self.rePswTF.secureTextEntry = YES;
    }
}
-(void)createUI{
    self.bgScro = [UIScrollView new];
    [self.view addSubview:self.bgScro];
    self.bgScro.sd_layout.spaceToSuperView(UIEdgeInsetsMake(kTopHeight, 0, KTabbarSafeBottomMargin, 0));
    
    UIView * titleView = [self getBaseView];
    titleView.sd_layout.leftSpaceToView(self.bgScro, 10).rightSpaceToView(self.bgScro, 10).topSpaceToView(self.bgScro, 15).heightIs(50);
    UILabel * titleLab = [self getTitleLab:NSLocalizedString(@"Title", nil) v:titleView];
    
    UIImage * icon = [[ImageFactory sharedInstance] imageForIndex:self.iconIdx];
    self.iconBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.iconBtn addTarget:self action:@selector(choseIconClick) forControlEvents:UIControlEventTouchUpInside];
    [self.iconBtn setImage:icon forState:UIControlStateNormal];
    [titleView addSubview:self.iconBtn];
    self.iconBtn.sd_layout.rightSpaceToView(titleView, 10).centerYEqualToView(titleView).widthIs(30).heightEqualToWidth();
    
    self.titleTF = [self configTF];
    self.titleTF.placeholder = NSLocalizedString(@"Input Title", nil);
    [titleView addSubview:self.titleTF];
    self.titleTF.sd_layout.leftSpaceToView(titleLab, 10).centerYEqualToView(titleView).heightIs(40).rightSpaceToView(self.iconBtn, 10);
    
    UIView * nameView = [self getBaseView];
    nameView.sd_layout.leftSpaceToView(self.bgScro, 10).rightSpaceToView(self.bgScro, 10).topSpaceToView(titleView, 10).heightIs(50);
    UILabel * nameLab = [self getTitleLab:NSLocalizedString(@"Account", nil) v:nameView];
    self.nameTF = [self configTF];
    self.nameTF.placeholder = NSLocalizedString(@"Input Account", nil);
    [nameView addSubview:self.nameTF];
    self.nameTF.sd_layout.leftSpaceToView(nameLab, 10).centerYEqualToView(nameView).heightIs(40).rightSpaceToView(nameView, 10);
    
    UIView * pswView = [self getBaseView];
    pswView.sd_layout.leftEqualToView(nameView).rightEqualToView(nameView).topSpaceToView(nameView, 10).heightIs(50);
    UILabel * pswLab = [self getTitleLab:NSLocalizedString(@"Password", nil) v:pswView];
    UIButton * eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [eyeBtn setImage:Image(@"eye_close") forState:UIControlStateNormal];
    [eyeBtn setImage:Image(@"eye_open") forState:UIControlStateSelected];
    [eyeBtn addTarget:self action:@selector(eyeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [pswView addSubview:eyeBtn];
    eyeBtn.sd_layout.rightSpaceToView(pswView, 5).centerYEqualToView(pswView).widthIs(30).heightEqualToWidth();
    self.pswTF = [self configTF];
    self.pswTF.placeholder = NSLocalizedString(@"Input Password", nil);
    self.pswTF.secureTextEntry = YES;
    [pswView addSubview:self.pswTF];
    self.pswTF.sd_layout.leftSpaceToView(pswLab, 10).centerYEqualToView(pswView).rightSpaceToView(eyeBtn, 5).heightIs(40);
    
    UIView * repeatView = [self getBaseView];
    repeatView.sd_layout.leftEqualToView(nameView).rightEqualToView(nameView).topSpaceToView(pswView, 10).heightIs(50);
    UILabel * repeatLab = [self getTitleLab:NSLocalizedString(@"Repeat Password", nil) v:repeatView];
    self.rePswTF = [self configTF];
    self.rePswTF.placeholder = NSLocalizedString(@"Enter your password again", nil);
    self.rePswTF.secureTextEntry = YES;
    [repeatView addSubview:self.rePswTF];
    self.rePswTF.sd_layout.leftSpaceToView(repeatLab, 10).centerYEqualToView(repeatView).rightSpaceToView(repeatView, 10).heightIs(40);
    
    UIView * dateView = [self getBaseView];
    dateView.sd_layout.leftEqualToView(nameView).rightEqualToView(nameView).topSpaceToView(repeatView, 10).heightIs(50);
    UILabel * dateLab = [self getTitleLab:NSLocalizedString(@"Expiration Date", nil) v:dateView];
    self.dateLab = [UILabel labelWithTitle:NSLocalizedString(@"Setting expiration date", nil) color:[UIColor lightGrayColor] font:M_Font alignment:NSTextAlignmentLeft];
    [dateView addSubview:self.dateLab];
    [self.dateLab addTarget:self action:@selector(choseDate)];
    self.dateLab.sd_layout.leftSpaceToView(dateLab, 10).centerYEqualToView(dateView).rightSpaceToView(dateView, 10).heightIs(40);
    
    UIView * urlView = [self getBaseView];
    urlView.sd_layout.leftEqualToView(nameView).rightEqualToView(nameView).topSpaceToView(dateView, 10).heightIs(50);
    UILabel * urlLab = [self getTitleLab:NSLocalizedString(@"Web Site", nil) v:urlView];
    self.urlTF = [self configTF];
    self.urlTF.placeholder = NSLocalizedString(@"Input Web Site (Not required)", nil);
    self.urlTF.keyboardType = UIKeyboardTypeURL;
    [urlView addSubview:self.urlTF];
    self.urlTF.sd_layout.leftSpaceToView(urlLab, 10).centerYEqualToView(urlView).rightSpaceToView(urlView, 10).heightIs(40);
    
    self.remarkTV = [QMUITextView new];
    self.remarkTV.font = M_Font;
    self.remarkTV.textColor = [UIColor normalColor:TextColor darkColor:UIColorWhite];
    self.remarkTV.cornerRadius = 5;
    self.remarkTV.placeholder = [NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"Note", nil),NSLocalizedString(@"Not required", nil)];
    self.remarkTV.placeholderColor = UIColorGrayLighten;
    [self.bgScro addSubview:self.remarkTV];
    self.remarkTV.sd_layout.leftEqualToView(nameView).rightEqualToView(nameView).topSpaceToView(urlView, 15).heightIs(120);
    
    CGFloat btnW = ceilf((SCREEN_WIDTH - 20 - 15)/2.0);
    UIButton * configBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [configBtn setTitle:NSLocalizedString(@"Password config", nil) forState:UIControlStateNormal];
    [configBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
    configBtn.backgroundColor = AssistColor;
    [configBtn addTarget:self action:@selector(configBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    configBtn.titleLabel.font = UIFontMake(M_FontSize + 2);
    configBtn.cornerRadius = 5;
    [self.bgScro addSubview:configBtn];
    configBtn.sd_layout.leftSpaceToView(self.bgScro, 10).topSpaceToView(self.remarkTV, 15).widthIs(btnW).heightIs(floor(AUTO(50)));
    
    UIButton * genBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [genBtn setTitle:NSLocalizedString(@"Generate", nil) forState:UIControlStateNormal];
    [genBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
    genBtn.backgroundColor = AssistBlueColor;
    [genBtn addTarget:self action:@selector(generatePswClick:) forControlEvents:UIControlEventTouchUpInside];
    genBtn.titleLabel.font = UIFontMake(M_FontSize + 2);
    genBtn.cornerRadius = 5;
    [self.bgScro addSubview:genBtn];
    genBtn.sd_layout.leftSpaceToView(self.bgScro, 10).topSpaceToView(configBtn, 10).widthIs(btnW).heightIs(floor(AUTO(50)));
    
    UIButton * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
    [saveBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
    saveBtn.backgroundColor = CertainBtnColor;
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.titleLabel.font = UIFontMake(M_FontSize + 2);
    saveBtn.cornerRadius = 5;
    [self.bgScro addSubview:saveBtn];
    if (self.entry) {
        saveBtn.sd_layout.rightSpaceToView(self.bgScro, 10).topEqualToView(configBtn).widthIs(btnW).bottomEqualToView(configBtn);
        
        UIButton * delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [delBtn setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
        [delBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
        delBtn.backgroundColor = CertainBtnColor;
        [delBtn addTarget:self action:@selector(delBtnClick) forControlEvents:UIControlEventTouchUpInside];
        delBtn.titleLabel.font = UIFontMake(M_FontSize + 2);
        delBtn.cornerRadius = 5;
        [self.bgScro addSubview:delBtn];
        delBtn.sd_layout.rightSpaceToView(self.bgScro, 10).topEqualToView(genBtn).widthIs(btnW).bottomEqualToView(genBtn);
        [self.bgScro setupAutoHeightWithBottomView:delBtn bottomMargin:20];
    }else{
        saveBtn.sd_layout.rightSpaceToView(self.bgScro, 10).topEqualToView(configBtn).widthIs(btnW).bottomEqualToView(genBtn);
        [self.bgScro setupAutoHeightWithBottomView:saveBtn bottomMargin:20];
    }
}
-(UITextField * )configTF{
    UITextField * tf = [UITextField new];
    tf.placeholderColor = UIColorGrayLighten;
    tf.font = M_Font;
    tf.textColor = [UIColor normalColor:TextColor darkColor:UIColorWhite];
    return tf;
}
-(UIView*)getBaseView{
    UIView * v = [UIView new];
    v.cornerRadius = 5;
    v.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:UIColorGrayDarken];
    [self.bgScro addSubview:v];
    return v;
}
-(UILabel *)getTitleLab:(NSString * )name v:(UIView*)v{
    int s = floor(AUTO(15));
    UILabel * lab = [UILabel labelWithTitle:name color:[UIColor normalColor:TextColor darkColor:UIColorWhite] fontSize:s];
    [v addSubview:lab];
    lab.sd_layout.leftSpaceToView(v, 10).centerYEqualToView(v).heightIs(s);
    [lab setSingleLineAutoResizeWithMaxWidth:300];
    return lab;
}
-(NSString * )generateRandomPswByNum:(int)num{
    NSString *string = @"";
    BOOL choseNum = [DLUserDefault userDefaultsModel].choseNum;
    BOOL choseAlpha = [DLUserDefault userDefaultsModel].choseAlpha;
    BOOL choseSym = [DLUserDefault userDefaultsModel].choseSymbol;
    if (choseNum && !choseAlpha && !choseSym) {
        for (int i = 0; i < num; i++) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }
    }else if(!choseNum && choseAlpha && !choseSym){
        string = [self returnLetterAndNumber:num filet:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
    }else if(!choseNum && !choseAlpha && choseSym){//符号
        int figure = (arc4random() % 15) + 33;
        char character = figure;
        NSString *tempString = [NSString stringWithFormat:@"%c", character];
        string = [string stringByAppendingString:tempString];
    }else if(choseNum && choseAlpha && !choseSym){
        string = [self returnLetterAndNumber:num filet:@"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
    }else if(choseNum && !choseAlpha && choseSym){
        string = [self returnLetterAndNumber:num filet:@"0123456789!\"#$%&'()*+,-./"];
    }else if(!choseNum && choseAlpha && choseSym){
        string = [self returnLetterAndNumber:num filet:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./"];
    }else{
        string = [self returnLetterAndNumber:num filet:@"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./"];
    }
    return string;
}
-(NSString *)returnLetterAndNumber:(int)num filet:(NSString*)filter{
    //定义一个包含数字，大小写字母的字符串
    NSString * strAll = filter;
    NSString * result = [[NSMutableString alloc]initWithCapacity:16];
    for (int i = 0; i < num; i++){
        //获取随机数
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    return result;
}
@end
